package com.cainiao.springboot.controller;

import com.cainiao.springboot.exception.UserNotExistException;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2021-10-30 22:00
 * 自定义异常处理器
 */
@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();
        //传入自己的状态码 4xx 5xx，否则就不会进入定制的错误页面的解析流程
        /*
         * BasicErrorController.errorHtml() (返回ModelAndView)方法调用了
         * AbstractErrorController.getStatus() 方法获取 HttpStatus。
         * 我们可以自定义来定义 status_code变量并返回
         *
         * Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
         * */
        request.setAttribute("javax.servlet.error.status_code", 420);
        map.put("code", "user.notexist");
        map.put("message", e.getMessage());
        //把我们定义的其他信息放进 request域中，在我们自定义的 ErrorAttribute进加入
        request.setAttribute("ext", map);
        return "forward:/error";
    }


    /*@ExceptionHandler(UserNotExistException.class)
    public String handleException33(Exception e, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();
        //传入字节的状态码 4xx 5xx
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

        request.setAttribute("javax.servlet.error.status_code", 500);
        map.put("code", "user.notexist");
        map.put("message", e.getMessage());
        request.setAttribute("ext", map);
        return "forward:/error";
    }*/
//    @ResponseBody //浏览器客户端返回的都是 josn数据
//    @ExceptionHandler(UserNotExistException.class)
//    public Map<String, Object> handleException(Exception e) {
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("code", "user.notexist");
//        map.put("message", e.getMessage());
//        return map;
//    }
}
